package com.moment.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import com.moment.model.LocationData;
import com.moment.util.Converter;
import com.moment.util.Geocoding;
import com.moment.webservice.Services;
import com.moment.webservice.ServicesProxy;



/**
 * Servlet implementation class LocationController
 */
@WebServlet("/LocationController")
public class LocationController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LocationController() {
        super();
        // TODO Auto-generated constructor stub
    }

    private void viewLocation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    	String target = null;
    	String lname = request.getParameter("lname");
    	String mobilenumber=(String)request.getSession().getAttribute("username");
    	if(lname!=null && !lname.equals(""))
    	{
//    		WebsProxy proxy=new WebsProxy();
//    		String output=proxy.fetchLocationDetails(mobilenumber, lname);
    		//--New CODE-------------
			Map<String,String> map=new HashMap<String,String>();
			map.put("method", "26");
			map.put("mnum",mobilenumber);
			map.put("nickname",lname);

			String json=new Converter().mapToJson(map);
			System.out.println("json String :"+json);
			Services serviceproxy=new ServicesProxy();
			
			String output=serviceproxy.service(json);
//---------------------------
			JSONArray jArray;
			JSONObject jobj = null;
			HttpSession session = request.getSession();
			
			LocationData locationData=new LocationData();
				System.out.println(output);
				
		 		try {
		 			jArray = new JSONArray(output);
		 			jobj = jArray.getJSONObject(0);
		 			
		 			locationData.setLocationname(jobj.getString("name"));
		 			locationData.setLocationadd(jobj.getString("address"));
		 			locationData.setInstrumentname(jobj.getString("Instrument"));
		 			locationData.setLocationid(Integer.valueOf(jobj.getString("Id")));
		 			session.setAttribute("locationObj", locationData);
					response.sendRedirect("/MMP/jsp/locationdetails.jsp");
		 			
		 		} catch (JSONException e) {
		 			// TODO Auto-generated catch block
		 			e.printStackTrace();
		 		}
			
    		target="jsp/viewlocation.jsp";
    		
    	}
    	//request.getRequestDispatcher(target).forward(request, response);
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    private void addLocation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    	
    	String lname = request.getParameter("lname");
    	String ltype = request.getParameter("ltype");
    	if(ltype.equalsIgnoreCase("view"))
    	{
    		viewLocation(request, response);
    	}
    	else
    	{
    		String laddress = request.getParameter("laddress");
    		String linstru = request.getParameter("linstru");
    		
    		
    		String mobilenumber=(String)request.getSession().getAttribute("username");
    
    		Geocoding geocode = new Geocoding();
    		String latlong = null;
    		try {
    			
    			latlong = geocode.GetLatlong(laddress);
    		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
    		}
    	String lat = null;
    	String longi = null;
    	String target = null;
    	String output = null;
		if(latlong!=null)
		{
	    	String[] ll = latlong.split(",");
	    	lat = ll[0];
	    	longi = ll[1];
		}
		if(ltype.equalsIgnoreCase("update"))
		{
			String lid = request.getParameter("lid");
			//--New CODE-------------
			Map<String,String> map=new HashMap<String,String>();
			map.put("method", "27");
		map.put("locationid",lid); map.put("mnum",mobilenumber);
					map.put("address",laddress);
					map.put("instrumentname",linstru);
					map.put("locationname",lname);

			String json=new Converter().mapToJson(map);
			System.out.println("json String :"+json);
			Services serviceproxy=new ServicesProxy();
			
			output=serviceproxy.service(json);
//---------------------------
			//output=proxy.updateLocation(lid, mobilenumber, laddress, linstru, lname);
			//System.out.println("update");
		}
		else
		{
			//--New CODE-------------
			Map<String,String> map=new HashMap<String,String>();
			map.put("method", "9");
		map.put("mnum",mobilenumber); map.put("locationname",lname);
					map.put("address",laddress);
					map.put("instrument",linstru);
					map.put("lat",lat);
					map.put("longi",longi);

			String json=new Converter().mapToJson(map);
			System.out.println("json String :"+json);
			Services serviceproxy=new ServicesProxy();
			
			 output=serviceproxy.service(json);
//---------------------------
			//output=proxy.addLocation(mobilenumber, lname, laddress, linstru, lat, longi);
		}
    	System.out.println("data from web Service:="+output);
		if(output.equals("Success")){
		/*	String out=proxy.fetchInstruments(mobilenumber);
			System.out.println(out);*/
			
		target="jsp/viewlocation.jsp";
		
		}else{
		target="jsp/addlocation.jsp";
	
		}
		response.sendRedirect(target);
	//	request.getRequestDispatcher(target).forward(request, response);
    	}
		
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		addLocation(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		addLocation(request, response);
	}

}
